package com.sls.nzdapplication.ui.activity.user;

import android.util.Patterns;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.alibaba.fastjson.JSONObject;
import com.sls.nzdapplication.R;
import com.sls.nzdapplication.httpclient.UserUtil;
import com.sls.nzdapplication.ui.activity.user.data.LoginRepository;
import com.sls.nzdapplication.ui.activity.user.data.model.LoggedInUser;
import com.sls.nzdapplication.util.SnowFlakeUtil;


public class LoginViewModel extends ViewModel {

    private MutableLiveData<LoginFormState> loginFormState = new MutableLiveData<>();
    private MutableLiveData<LoginResult> loginResult = new MutableLiveData<>();

    public LoggedInUser getLoggedInUser() {
        return loggedInUser;
    }

    private LoggedInUser loggedInUser;
    private LoginRepository loginRepository;

    LoginViewModel(LoginRepository loginRepository) {
        this.loginRepository = loginRepository;
    }

    public LiveData<LoginFormState> getLoginFormState() {
        return loginFormState;
    }

    public LiveData<LoginResult> getLoginResult() {
        return loginResult;
    }

    public JSONObject login(String username, String password,String server) {
        // can be launched in a separate asynchronous job
       JSONObject loginInfo = new JSONObject();
        loginInfo.put("username",username);
        loginInfo.put("password", SnowFlakeUtil.SHA256(password));
        return  UserUtil.loginPostJsonParams(server,loginInfo.toJSONString());
    }

    public void loginDataChanged(String username, String password,String server) {
        if (!isUserNameValid(username)) {
            loginFormState.setValue(new LoginFormState(R.string.invalid_username, null,null));
        } else if (!isPasswordValid(password)) {
            loginFormState.setValue(new LoginFormState(null, R.string.invalid_password,null));
        } else if (!isServerValid(server)){
            loginFormState.setValue(new LoginFormState(null, null,R.string.invalid_server));
        }
        else {
            loginFormState.setValue(new LoginFormState(true));
        }
    }

    // A placeholder username validation check
    private boolean isUserNameValid(String username) {
        if (username == null) {
            return false;
        }
        if (username.contains("@")) {
            return Patterns.EMAIL_ADDRESS.matcher(username).matches();
        } else {
            return !username.trim().isEmpty();
        }
    }

    // A placeholder password validation check
    private boolean isPasswordValid(String password) {
        return password != null && password.trim().length() > 5;
    }

    private boolean isServerValid(String server) {
        return server != null && Patterns.WEB_URL.matcher(server).matches();
    }


}